<template>
  <view class="survey-category-page">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="navbar-left" @click="navigateBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <view class="navbar-title">{{ categoryName }}</view>
      <view class="navbar-right">
        <uni-icons type="search" size="24" color="#333" @click="showSearch"></uni-icons>
      </view>
    </view>

    <!-- 筛选和排序栏 -->
    <view class="filter-bar">
      <view class="filter-item" @click="showFilterPopup">
        <text>筛选</text>
        <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
      </view>
      <view class="filter-item" @click="showSortPopup">
        <text>排序</text>
        <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
        <view v-if="currentSort" class="sort-tag">{{ currentSortText }}</view>
      </view>
      <view class="filter-tags">
        <view 
          class="filter-tag" 
          v-for="(tag, index) in activeFilterTags" 
          :key="index"
          @click="removeFilterTag(index)"
        >
          <text>{{ tag }}</text>
          <uni-icons type="close" size="14" color="#999"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 问卷列表 -->
    <scroll-view class="survey-list" scroll-y>
      <view 
        class="survey-card" 
        v-for="(survey, index) in filteredSurveys" 
        :key="index"
        @click="gotoSurveyDetail(survey.surveyId)"
      >
        <!-- 问卷标题和基本信息 -->
        <view class="survey-header">
          <view class="survey-title">{{ survey.title }}</view>
          <view class="survey-meta">
            <view class="meta-item">
              <uni-icons type="clock" size="14" color="#999"></uni-icons>
              <text>{{ survey.estimatedTime }}分钟</text>
            </view>
            <view class="meta-item">
              <uni-icons type="people" size="14" color="#999"></uni-icons>
              <text>{{ survey.participants }}人参与</text>
            </view>
          </view>
        </view>
        
        <!-- 问卷描述 -->
        <view class="survey-desc">{{ survey.description }}</view>
        
        <!-- 问卷标签和奖励 -->
        <view class="survey-footer">
          <view class="survey-tags">
            <view class="survey-tag" v-for="(tag, tIndex) in survey.tags" :key="tIndex">
              {{ tag }}
            </view>
          </view>
          
          <view class="survey-reward" v-if="survey.reward">
            <uni-icons type="gift" size="16" color="#ff9900"></uni-icons>
            <text>{{ survey.reward }}</text>
          </view>
        </view>
        
        <!-- 分隔线 -->
        <view class="divider" v-if="index !== filteredSurveys.length - 1"></view>
      </view>
      
      <!-- 空状态 -->
      <view v-if="filteredSurveys.length === 0" class="empty-state">
        <uni-icons type="empty" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">暂无符合条件的问卷</text>
        <button class="reset-btn" @click="resetFilters">重置筛选条件</button>
      </view>
      
      <!-- 底部加载更多 -->
      <view v-if="filteredSurveys.length > 0" class="load-more" @click="loadMore">
        <text>{{ loadingMore ? '加载中...' : '加载更多' }}</text>
      </view>
    </scroll-view>

    <!-- 筛选弹窗 -->
    <uni-popup 
      ref="filterPopup" 
      type="bottom" 
      :mask="true"
      @close="onFilterPopupClose"
    >
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">筛选条件</text>
          <text class="popup-reset" @click="resetFilterOptions">重置</text>
        </view>
        
        <!-- 奖励类型筛选 -->
        <view class="filter-section">
          <view class="filter-section-title">奖励类型</view>
          <view class="filter-options">
            <view 
              class="filter-option" 
              v-for="(option, index) in rewardOptions" 
              :key="index"
              @click="selectRewardOption(index)"
              :class="{ selected: filterOptions.reward === option.value }"
            >
              <text>{{ option.label }}</text>
            </view>
          </view>
        </view>
        
        <!-- 时长筛选 -->
        <view class="filter-section">
          <view class="filter-section-title">预计时长</view>
          <view class="filter-options">
            <view 
              class="filter-option" 
              v-for="(option, index) in timeOptions" 
              :key="index"
              @click="selectTimeOption(index)"
              :class="{ selected: filterOptions.time === option.value }"
            >
              <text>{{ option.label }}</text>
            </view>
          </view>
        </view>
        
        <!-- 按钮 -->
        <view class="popup-buttons">
          <button class="cancel-btn" @click="closeFilterPopup">取消</button>
          <button class="confirm-btn" @click="confirmFilter">确认</button>
        </view>
      </view>
    </uni-popup>

    <!-- 排序弹窗 -->
    <uni-popup 
      ref="sortPopup" 
      type="bottom" 
      :mask="true"
    >
      <view class="popup-content sort-popup">
        <view class="popup-header">
          <text class="popup-title">排序方式</text>
        </view>
        
        <view class="sort-options">
          <view 
            class="sort-option" 
            v-for="(option, index) in sortOptions" 
            :key="index"
            @click="selectSortOption(option.value)"
            :class="{ selected: currentSort === option.value }"
          >
            <text>{{ option.label }}</text>
            <uni-icons 
              v-if="currentSort === option.value" 
              type="check" 
              size="18" 
              color="#007aff"
            ></uni-icons>
          </view>
        </view>
        
        <button class="cancel-btn full-width" @click="closeSortPopup">取消</button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 分类ID和名称（从路由参数获取）
      categoryId: null,
      categoryName: "",
      
      // 问卷数据
      allSurveys: [],
      filteredSurveys: [],
      
      // 筛选和排序
      filterOptions: {
        reward: "all",
        time: "all"
      },
      currentSort: "newest",
      activeFilterTags: [],
      loadingMore: false,
      
      // 筛选选项
      rewardOptions: [
        { label: "全部", value: "all" },
        { label: "有奖励", value: "reward" },
        { label: "无奖励", value: "no_reward" }
      ],
      timeOptions: [
        { label: "全部", value: "all" },
        { label: "5分钟以内", value: "short" },
        { label: "5-10分钟", value: "medium" },
        { label: "10分钟以上", value: "long" }
      ],
      sortOptions: [
        { label: "最新发布", value: "newest" },
        { label: "参与人数最多", value: "most_participants" },
        { label: "奖励最高", value: "highest_reward" },
        { label: "时长最短", value: "shortest_time" }
      ]
    };
  },
  computed: {
    // 排序文本显示
    currentSortText() {
      const option = this.sortOptions.find(item => item.value === this.currentSort);
      return option ? option.label : "";
    }
  },
  onLoad(options) {
    // 获取分类ID和名称
    this.categoryId = options.categoryId;
    console.log('接收到的分类ID:',this.categoryId)
    this.categoryName = options.name || "问卷列表";
    
    // 加载问卷数据
    this.loadSurveyData();
  },
  methods: {
    // 加载问卷数据
    loadSurveyData() {
      // 显示加载中
      uni.showLoading({
        title: '加载中...'
      });
      
      // 调用API获取问卷数据
      this.fetchQuestionnaresByCategory();
    },
    
    // 从API获取问卷数据
    fetchQuestionnaresByCategory() {
      // 构建请求URL
      const apiUrl = 'https://wxapi.xiaoyiwl.cn/wx_questionnare/get_questionnares_by_id.php';
      
      // 发起请求
      uni.request({
        url: apiUrl,
        method: 'GET',
        data: {
          category_id: this.categoryId
        },
        success: (res) => {
          // 隐藏加载提示
          uni.hideLoading();
          
          // 检查返回数据
          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            // 处理返回的问卷数据
            const questionnaires = res.data.data || [];
            console.log(res.data.data)
            // 转换数据格式以适应当前模板
            this.allSurveys = questionnaires.map(item => ({
              surveyId: item.surveyID || '',
              id: item.id || '',
              title: item.title || '未命名问卷',
              description: item.description || '暂无描述',
              estimatedTime: item.estimated_time || 5,
              participants: item.participants || 0,
              tags: item.tags ? item.tags.split(',') : [],
              reward: item.reward || '',
              publishTime: item.publish_time || new Date().toISOString().split('T')[0]
            }));

            // 应用筛选和排序
            this.applyFiltersAndSort();
          } else {
            // 处理错误情况
            console.error('获取问卷数据失败:', res);
            uni.showToast({
              title: '获取问卷数据失败',
              icon: 'none'
            });
            
            // 使用空数组
            this.allSurveys = [];
            this.filteredSurveys = [];
          }
        },
        fail: (err) => {
          // 隐藏加载提示
          uni.hideLoading();
          
          // 显示错误提示
          console.error('请求失败:', err);
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
          
          // 使用空数组
          this.allSurveys = [];
          this.filteredSurveys = [];
        }
      });
    },
    
    // 应用筛选和排序
    applyFiltersAndSort() {
      let result = [...this.allSurveys];
      
      // 应用筛选
      if (this.filterOptions.reward === "reward") {
        result = result.filter(survey => survey.reward);
      } else if (this.filterOptions.reward === "no_reward") {
        result = result.filter(survey => !survey.reward);
      }
      
      if (this.filterOptions.time === "short") {
        result = result.filter(survey => survey.estimatedTime <= 5);
      } else if (this.filterOptions.time === "medium") {
        result = result.filter(survey => survey.estimatedTime > 5 && survey.estimatedTime <= 10);
      } else if (this.filterOptions.time === "long") {
        result = result.filter(survey => survey.estimatedTime > 10);
      }
      
      // 更新筛选标签
      this.updateFilterTags();
      
      // 应用排序
      if (this.currentSort === "newest") {
        result.sort((a, b) => new Date(b.publishTime) - new Date(a.publishTime));
      } else if (this.currentSort === "most_participants") {
        result.sort((a, b) => b.participants - a.participants);
      } else if (this.currentSort === "highest_reward") {
        result.sort((a, b) => {
          // 简单处理奖励排序，实际项目可能需要更复杂的逻辑
          const rewardA = a.reward ? parseInt(a.reward) || 0 : 0;
          const rewardB = b.reward ? parseInt(b.reward) || 0 : 0;
          return rewardB - rewardA;
        });
      } else if (this.currentSort === "shortest_time") {
        result.sort((a, b) => a.estimatedTime - b.estimatedTime);
      }
      
      this.filteredSurveys = result;
    },
    
    // 更新筛选标签
    updateFilterTags() {
      const tags = [];
      
      // 奖励类型标签
      const rewardOption = this.rewardOptions.find(item => item.value === this.filterOptions.reward);
      if (rewardOption && rewardOption.value !== "all") {
        tags.push(rewardOption.label);
      }
      
      // 时长标签
      const timeOption = this.timeOptions.find(item => item.value === this.filterOptions.time);
      if (timeOption && timeOption.value !== "all") {
        tags.push(timeOption.label);
      }
      
      this.activeFilterTags = tags;
    },
    
    // 显示筛选弹窗
    showFilterPopup() {
      this.$refs.filterPopup.open();
    },
    
    // 关闭筛选弹窗
    closeFilterPopup() {
      this.$refs.filterPopup.close();
    },
    
    // 筛选弹窗关闭时
    onFilterPopupClose() {
      // 可以在这里处理弹窗关闭后的逻辑
    },
    
    // 显示排序弹窗
    showSortPopup() {
      this.$refs.sortPopup.open();
    },
    
    // 关闭排序弹窗
    closeSortPopup() {
      this.$refs.sortPopup.close();
    },
    
    // 选择奖励筛选选项
    selectRewardOption(index) {
      this.filterOptions.reward = this.rewardOptions[index].value;
    },
    
    // 选择时长筛选选项
    selectTimeOption(index) {
      this.filterOptions.time = this.timeOptions[index].value;
    },
    
    // 选择排序选项
    selectSortOption(value) {
      this.currentSort = value;
      this.applyFiltersAndSort();
      this.closeSortPopup();
    },
    
    // 确认筛选
    confirmFilter() {
      this.applyFiltersAndSort();
      this.closeFilterPopup();
    },
    
    // 重置筛选选项
    resetFilterOptions() {
      this.filterOptions = {
        reward: "all",
        time: "all"
      };
    },
    
    // 移除筛选标签
    removeFilterTag(index) {
      const tagText = this.activeFilterTags[index];
      
      // 找到对应的筛选条件并重置
      if (this.rewardOptions.some(item => item.label === tagText)) {
        this.filterOptions.reward = "all";
      } else if (this.timeOptions.some(item => item.label === tagText)) {
        this.filterOptions.time = "all";
      }
      
      // 重新应用筛选
      this.applyFiltersAndSort();
    },
    
    // 重置所有筛选条件
    resetFilters() {
      this.resetFilterOptions();
      this.currentSort = "newest";
      this.applyFiltersAndSort();
    },
    
    // 加载更多
    loadMore() {
      if (this.loadingMore) return;
      
      this.loadingMore = true;
      
      // 模拟加载更多数据
      setTimeout(() => {
        // 复制现有数据并修改ID和发布时间，模拟新数据
        const newSurveys = this.allSurveys.map(survey => ({
          ...survey,
          id: survey.id + 1000,
          publishTime: "2023-05-20"
        }));
        
        this.allSurveys = [...this.allSurveys, ...newSurveys];
        this.applyFiltersAndSort();
        this.loadingMore = false;
      }, 1000);
    },
    
    // 返回上一页
    navigateBack() {
      uni.navigateBack({
        delta: 1
      });
    },
    
    // 显示搜索
    showSearch() {
      uni.showToast({
        title: "搜索功能待实现",
        icon: "none"
      });
    },
    
    // 进入问卷详情
    // 通过id 进入问卷
    gotoSurveyDetail(surveyId) {
      // 需要再次登录判断
      uni.navigateTo({
        url: `./testDetail?surveyId=${surveyId}`
      });
    }
  }
};
</script>

<style scoped lang="scss">
.survey-category-page {
  background-color: #f5f5f7;
  min-height: 100vh;
}

// 导航栏样式
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;
  padding: 0 16px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  
  .navbar-left, .navbar-right {
    width: 44px;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .navbar-title {
    font-size: 17px;
    font-weight: 500;
    color: #333;
    flex: 1;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

// 筛选和排序栏
.filter-bar {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  flex-wrap: wrap;
  gap: 8px;
  
  .filter-item {
    display: flex;
    align-items: center;
    padding: 6px 12px;
    background-color: #f5f5f5;
    border-radius: 16px;
    font-size: 14px;
    color: #333;
    margin-right: 8px;
    
    uni-icons {
      margin-left: 4px;
    }
    
    .sort-tag {
      margin-left: 6px;
      font-size: 12px;
      color: #007aff;
    }
  }
  
  .filter-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 4px;
    
    .filter-tag {
      display: flex;
      align-items: center;
      padding: 4px 10px;
      background-color: #e8f4fd;
      border-radius: 14px;
      font-size: 12px;
      color: #007aff;
      
      uni-icons {
        margin-left: 6px;
      }
    }
  }
}

// 问卷列表
.survey-list {
  padding: 16px;
  height: calc(100vh - 116px);
  
  .survey-card {
    background-color: #fff;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: background-color 0.2s ease;
    margin-right: 26px;
    &:active {
      background-color: #f9f9f9;
    }
    
    .survey-header {
      margin-bottom: 12px;
      
      .survey-title {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        margin-bottom: 8px;
        line-height: 1.4;
      }
      
      .survey-meta {
        display: flex;
        gap: 16px;
        font-size: 12px;
        color: #999;
        
        .meta-item {
          display: flex;
          align-items: center;
          
          uni-icons {
            margin-right: 4px;
          }
        }
      }
    }
    
    .survey-desc {
      font-size: 14px;
      color: #666;
      line-height: 1.5;
      margin-bottom: 16px;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    
    .survey-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .survey-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .survey-tag {
          font-size: 12px;
          color: #666;
          background-color: #f5f5f5;
          padding: 2px 8px;
          border-radius: 12px;
        }
      }
      
      .survey-reward {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #ff9900;
        font-weight: 500;
        
        uni-icons {
          margin-right: 4px;
        }
      }
    }
    
    .divider {
      height: 1px;
      background-color: #f5f5f5;
      margin-top: 16px;
    }
  }
  
  // 空状态
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300px;
    
    .empty-text {
      margin: 16px 0;
      font-size: 14px;
      color: #999;
    }
    
    .reset-btn {
      background-color: #007aff;
      color: #fff;
      border-radius: 4px;
      padding: 8px 16px;
      font-size: 14px;
    }
  }
  
  // 加载更多
  .load-more {
    text-align: center;
    padding: 16px;
    font-size: 14px;
    color: #666;
    background-color: #fff;
    border-radius: 8px;
    margin-top: 12px;
  }
}

// 弹窗样式
.popup-content {
  background-color: #fff;
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;
  padding: 16px;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
    
    .popup-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
    
    .popup-reset {
      font-size: 14px;
      color: #007aff;
    }
  }
  
  .filter-section {
    margin-bottom: 24px;
    
    .filter-section-title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      margin-bottom: 12px;
    }
    
    .filter-options {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
      
      .filter-option {
        padding: 8px 16px;
        background-color: #f5f5f5;
        border-radius: 20px;
        font-size: 14px;
        color: #333;
        
        &.selected {
          background-color: #007aff;
          color: #fff;
        }
      }
    }
  }
  
  .popup-buttons {
    display: flex;
    gap: 12px;
    margin-top: 16px;
    
    .cancel-btn, .confirm-btn {
      flex: 1;
      height: 44px;
      border-radius: 8px;
      font-size: 16px;
    }
    
    .cancel-btn {
      background-color: #f5f5f5;
      color: #333;
    }
    
    .confirm-btn {
      background-color: #007aff;
      color: #fff;
    }
  }
  
  .full-width {
    width: 100%;
  }
}

// 排序弹窗
.sort-popup {
  .sort-options {
    .sort-option {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 14px 0;
      border-bottom: 1px solid #eee;
      font-size: 16px;
      color: #333;
      
      &:last-child {
        border-bottom: none;
      }
    }
  }
}
</style>
